package com.study.jyg.rxjava2study.activity.wifidevicesearch;

import android.content.Context;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.study.jyg.rxjava2study.R;
import com.study.jyg.rxjava2study.base.BasicActivity;

public class TestWifiActivity extends BasicActivity {


    private final String SERVICE_TYPE = "service_type";

    private NsdManager mNsdManager = null;

    private NsdManager.RegistrationListener mRegistrationListener;//NSD服务端注册监听



    private NsdManager.DiscoveryListener mNSDDiscoveryListener = null;    //    搜寻监听器
    private NsdManager.ResolveListener mNSDResolveListener = null;//    解析监听器
    private final String mServerType = "_http._tcp.";//扫描网络  代表基于tcp的http协议

    private TextView tvLog;
    @Override
    protected int getLayout() {
        return R.layout.activity_test2;
    }

    @Override
    protected void initView() {
        tvLog = findViewById(R.id.tvLog);
        initNSD();//初始化NSD
        initializeRegistrationListener();//实例化注册监听器
        log("实例化服务器注册监听器");
        registerService("wifitest", 1233);
        log("进行注册服务器");
        initNSDDiscoveryListener();//注册NSD服务网络的监听 发现NSD网络后会在对应的方法回调
        log("注册NSD服务网络的监听");
        initNSDResolveListener();//注册解析NSD网络的监听 ,解析NSD数据后回调
        log("注册解析NSD网络的监听");
        discoveryNSDServer(new View(mContext));//发现周边的NSD相关网络
        log("发现周边的NSD相关网络");
    }

    /**
     * 进行注册
     * @param serviceName
     * @param port
     */
    private void registerService(String serviceName, int port) {
        NsdServiceInfo serviceInfo = new NsdServiceInfo();
        serviceInfo.setServiceName(serviceName);
        serviceInfo.setPort(port);
        serviceInfo.setServiceType("_http._tcp.");//客户端发现服务器是需要对应的这个Type字符串
        mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
    }
    /**
     * 实例化注册监听器
     */
    private void initializeRegistrationListener() {
        mRegistrationListener = new NsdManager.RegistrationListener() {
            @Override
            public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
                Log.e(TAG, "NsdServiceInfo onRegistrationFailed");
                log("NsdServiceInfo onRegistrationFailed");

            }

            @Override
            public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
                Log.i(TAG, "onUnregistrationFailed serviceInfo: " + serviceInfo + " ,errorCode:" + errorCode);
                log("onUnregistrationFailed serviceInfo: " + serviceInfo + " ,errorCode:" + errorCode);

            }

            @Override
            public void onServiceRegistered(NsdServiceInfo serviceInfo) {
                Log.i(TAG, "onServiceRegistered: " + serviceInfo);
                log("onServiceRegistered: " + serviceInfo);

            }

            @Override
            public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
                Log.i(TAG, "onServiceUnregistered serviceInfo: " + serviceInfo);
                log("onServiceUnregistered serviceInfo: " + serviceInfo);

            }
        };
    }

    /**
     * 初始化NSDManager
     */
    private void initNSD(){
        mNsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE);
    }

    /**
     * 注册NSD服务网络的监听，发现NSD网络后会在对应的方法回调
     */
    private void initNSDDiscoveryListener() {
        mNSDDiscoveryListener = new NsdManager.DiscoveryListener() {
            @Override
            public void onStartDiscoveryFailed(String serviceType, int errorCode) {
                log("onStartDiscoveryFailed--> " + serviceType + ":" + errorCode);
                Log.e(TAG, "onStartDiscoveryFailed--> " + serviceType + ":" + errorCode);
            }

            @Override
            public void onStopDiscoveryFailed(String serviceType, int errorCode) {
                log("onStopDiscoveryFailed--> " + serviceType + ":" + errorCode);
                Log.e(TAG, "onStopDiscoveryFailed--> " + serviceType + ":" + errorCode);
            }

            @Override
            public void onDiscoveryStarted(String serviceType) {
                log("onDiscoveryStarted--> " + serviceType );
                Log.e(TAG, "onDiscoveryStarted--> " + serviceType );
            }

            @Override
            public void onDiscoveryStopped(String serviceType) {
                log("onDiscoveryStopped--> " + serviceType );
                Log.e(TAG, "onDiscoveryStopped--> " + serviceType );
            }

            @Override
            public void onServiceFound(NsdServiceInfo serviceInfo) {//关键的回调方法
                //这里的 serviceInfo里面只有NSD服务器的主机名，要解析后才能得到该主机名的其他数据信息
                log("onServiceFound Info: --> " + serviceInfo);
                Log.e(TAG, "onServiceFound Info: --> " + serviceInfo);
                //开始解析数据
                resoleServer(serviceInfo);
            }

            @Override
            public void onServiceLost(NsdServiceInfo serviceInfo) {
                log("onServiceLost--> " + serviceInfo);
                Log.e(TAG, "onServiceLost--> " + serviceInfo);
            }
        };
    }

    /**
     * 注册解析NSD网络的监听 ,解析NSD数据后回调
     */
    private void initNSDResolveListener() {
        mNSDResolveListener = new NsdManager.ResolveListener() {
            @Override
            public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {

            }

            @Override
            public void onServiceResolved(NsdServiceInfo serviceInfo) {//到这里就是我们要的最终数据信息
                log("resolution : " + serviceInfo.getServiceName() + " \n host_from_server: " + serviceInfo.getHost() +
                        "\n port from server: " + serviceInfo.getPort());
                Log.e(TAG, "resolution : " + serviceInfo.getServiceName() + " \n host_from_server: " + serviceInfo.getHost() +
                        "\n port from server: " + serviceInfo.getPort());
                String hostAddress = serviceInfo.getHost().getHostAddress();
                log("hostAddress ip--> " + hostAddress);
                Log.e(TAG, "hostAddress ip--> " + hostAddress );


            }
        };

    }

    /**
     * 发现周边的NSD相关网络
     * @param view
     */
    public void discoveryNSDServer(View view) {
        //三个参数
        //第一个参数要和NSD服务器端定的ServerType一样，
        //第二个参数是固定的
        //第三个参数是扫描监听器
        mNsdManager.discoverServices(mServerType, NsdManager.PROTOCOL_DNS_SD, mNSDDiscoveryListener);
    }

    /**
     * 对得到的NDSServiceInfo进行解析
     * @param nsdServiceInfo
     */
    public void resoleServer(NsdServiceInfo nsdServiceInfo){

        //第一个参数是扫描得到的对象，第二个参数是解析监听对象
        mNsdManager.resolveService(nsdServiceInfo, mNSDResolveListener);
    }

    private void log(String text){
        String log = tvLog.getText().toString();
        if (TextUtils.isEmpty(log)){
            tvLog.setText(text);
        }else {
            tvLog.setText(String.format("%s\n%s", log, text));
        }
    }
}